//
//  PullToReloadView.m
//  SocialEngine
//
//  Created by Nguyen Ba Tan on 5/24/13.
//  Copyright (c) 2013 Home. All rights reserved.
//

#import "PullToReloadView.h"

#define TEXT_COLOR [UIColor colorWithRed:87.0/255.0 green:108.0/255.0 blue:137.0/255.0 alpha:1.0]
#define FLIP_ANIMATION_DURATION 0.18f

@implementation PullToReloadView {
    RefreshState refreshingState;
	UILabel *lbLastUpdate;
	UILabel *lbStatus;
	CALayer *imgArrow;
	UIActivityIndicatorView *indicattorView;
}

@synthesize delegate = _delegate;

- (id)initWithFrame:(CGRect) frame {
    if (self = [super initWithFrame:frame]) {
		
		self.autoresizingMask = UIViewAutoresizingFlexibleWidth;
		self.backgroundColor = [UIColor colorWithRed:226.0 / 255.0 green:231.0 / 255.0 blue:237.0 / 255.0 alpha:1.0];
        
		UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, frame.size.height - 30.0f, self.frame.size.width, 20.0f)];
		label.autoresizingMask = UIViewAutoresizingFlexibleWidth;
		label.font = [UIFont systemFontOfSize:12.0f];
		label.textColor = TEXT_COLOR;
		label.shadowColor = [UIColor colorWithWhite:0.9f alpha:1.0f];
		label.shadowOffset = CGSizeMake(0.0f, 1.0f);
		label.backgroundColor = [UIColor clearColor];
		label.textAlignment = UITextAlignmentCenter;
		[self addSubview:label];
		lbLastUpdate = label;
		
		label = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, frame.size.height - 48.0f, self.frame.size.width, 20.0f)];
		label.autoresizingMask = UIViewAutoresizingFlexibleWidth;
		label.font = [UIFont boldSystemFontOfSize:13.0f];
		label.textColor = TEXT_COLOR;
		label.shadowColor = [UIColor colorWithWhite:0.9f alpha:1.0f];
		label.shadowOffset = CGSizeMake(0.0f, 1.0f);
		label.backgroundColor = [UIColor clearColor];
		label.textAlignment = UITextAlignmentCenter;
		[self addSubview:label];
		lbStatus = label;
		
		CALayer *layer = [CALayer layer];
		layer.frame = CGRectMake(25.0f, frame.size.height - 65.0f, 30.0f, 55.0f);
		layer.contentsGravity = kCAGravityResizeAspect;
		layer.contents = (id)[UIImage imageNamed:@"blueArrow.png"].CGImage;
		
// #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 40000
		if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
			layer.contentsScale = [[UIScreen mainScreen] scale];
		}
// #endif
		
		[[self layer] addSublayer:layer];
		imgArrow = layer;
		
		UIActivityIndicatorView *view = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
		view.frame = CGRectMake(25.0f, frame.size.height - 38.0f, 20.0f, 20.0f);
		[self addSubview:view];
		indicattorView = view;
				
		[self setRefreshState:RefreshNormal];
		
    }
	
    return self;	
}

// Update date when reload success
- (void) refreshLastUpdatedDate {	
	if ([_delegate respondsToSelector:@selector(refreshTableHeaderLastUpdated:)]) {
		NSDate *date = [_delegate refreshTableHeaderLastUpdated:self];
		
		NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
		[formatter setAMSymbol:@"AM"];
		[formatter setPMSymbol:@"PM"];
		[formatter setDateFormat:@"MM/dd/yyyy hh:mm:a"];
		lbLastUpdate.text = [NSString stringWithFormat:@"Last Updated: %@", [formatter stringFromDate:date]];
		[[NSUserDefaults standardUserDefaults] setObject:lbLastUpdate.text forKey:@"LastRefresh_Date"];
		[[NSUserDefaults standardUserDefaults] synchronize];
	} else {
		lbLastUpdate.text = nil;
	}
}

- (void) setRefreshState:(RefreshState) _state{
	switch (_state) {
		case RefreshPulling: {
            lbStatus.text = @"Release to refresh...";
			[CATransaction begin];
			[CATransaction setAnimationDuration:FLIP_ANIMATION_DURATION];
			imgArrow.transform = CATransform3DMakeRotation((M_PI / 180.0) * 180.0f, 0.0f, 0.0f, 1.0f);
			[CATransaction commit];
			
			break;
        }

		case RefreshNormal: {
			if (refreshingState == RefreshPulling) {
				[CATransaction begin];
				[CATransaction setAnimationDuration:FLIP_ANIMATION_DURATION];
				imgArrow.transform = CATransform3DIdentity;
				[CATransaction commit];
			}
			
			lbStatus.text = @"Pull down to refresh...";
			[indicattorView stopAnimating];
			[CATransaction begin];
			[CATransaction setValue:(id) kCFBooleanTrue forKey:kCATransactionDisableActions];
			imgArrow.hidden = NO;
			imgArrow.transform = CATransform3DIdentity;
			[CATransaction commit];
			
			[self refreshLastUpdatedDate];
			
			break;
        }
			
		case RefreshLoading: {
            lbStatus.text = @"Loading...";
			[indicattorView startAnimating];
			[CATransaction begin];
			[CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions];
			imgArrow.hidden = YES;
			[CATransaction commit];
			
			break;
        }
		default:
			break;
	}
	
	refreshingState = _state;
}

// Action when user scroll the view
// Case : Is loading or not ...
- (void) disposeScrollViewDidScroll:(UIScrollView *) scrollView {
	if (refreshingState == RefreshLoading) {
		// is loading state
		CGFloat offset = MAX(scrollView.contentOffset.y * -1, 0);
		offset = MIN(offset, 60);
		scrollView.contentInset = UIEdgeInsetsMake(offset, 0.0f, 0.0f, 0.0f);
		
	} else if (scrollView.isDragging) {
        // user is dragging view
        
		BOOL _loading = NO;
        
        // detect new state of table
		if ([_delegate respondsToSelector:@selector(detectTableIsLoading:)]) {
			_loading = [_delegate detectTableIsLoading:self];
		}
		
		if (refreshingState == RefreshPulling && scrollView.contentOffset.y > -65.0f && scrollView.contentOffset.y < 0.0f && !_loading) {
			[self setRefreshState:RefreshNormal];
		} else if (refreshingState == RefreshNormal && scrollView.contentOffset.y < -65.0f && !_loading) {
			[self setRefreshState:RefreshPulling];
		}
		
		if (scrollView.contentInset.top != 0) {
			scrollView.contentInset = UIEdgeInsetsZero;
		}		
	}	
}

// action when dragging end
- (void) disposeScrollViewDidEndDragging:(UIScrollView *) scrollView {
	BOOL _loading = NO;
    
	if ([_delegate respondsToSelector:@selector(detectTableIsLoading:)]) {
		_loading = [_delegate detectTableIsLoading:self];
	}
	
	if (scrollView.contentOffset.y <= - 65.0f && !_loading) {
		if ([_delegate respondsToSelector:@selector(startRefreshAction:)]) {
			[_delegate startRefreshAction:self];
		}
		
		[self setRefreshState:RefreshLoading];
		[UIView beginAnimations:nil context:NULL];
		[UIView setAnimationDuration:0.2];
		scrollView.contentInset = UIEdgeInsetsMake(60.0f, 0.0f, 0.0f, 0.0f);
		[UIView commitAnimations];
		
	}	
}

// after realoaing success, pull the view up to normal
- (void) actionScrollViewDidFinishedLoading:(UIScrollView *)scrollView {
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration:.3];
	[scrollView setContentInset:UIEdgeInsetsMake(0.0f, 0.0f, 0.0f, 0.0f)];
	[UIView commitAnimations];
	
	[self setRefreshState:RefreshNormal];
}

@end
